ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Location Strategy in Angular

In this tutorial, we look at the Location Strategy (Angular Routing Strategy) supported by the Angular routing module.Angular Supports PathlocationStrategy and HashLocationStrategy. We will look at what is client-side routing and how it works. We take a look at how hash style HTML5 routing works and the pros and cons of each. Finally, we will learn how to build the Angular application using the PathLocationStrategy (HTML5 routing ) HashLocationStrategy.(hash style Routing )

Location Strategies in Angular Router

Being a Single Page Application, the Angular applications should not send the URL to the server and should not reload the page, every time the user requests a new page.

The URLs are strictly local in Angular Apps. The Angular router navigates to the new component and renders its template and updates the history and URL for the view. All this happens locally in the browser.

There are two ways, by which Angular achieves this. These are called Location Strategies.

The Location Strategy defines how our URL/Request is resolved. It also determines how your URL will look like

Angular supports two Location Strategies:

  1. HashLocationStrategy Where URL looks like http://localhost:4200/#/product
  2. PathLocationStrategy Where URL looks like http://localhost:4200/product

Before going further let's first understand what client-side routing is

Client-Side Routing

In a Multi-page web application, Every time the application needs to display a page it has to send a request to the web server. You can do that by either typing the URL in the address bar, or clicking on the Menu link/ button. Every such action results in the browser sending a new request to the Web server

But, Angular Applications are single-page applications or SPA.

All the components are displayed on a single page

In a Typical Single Page Application, when the Web application is loaded it loads a single HTML page. Whenever the user interacts with the page, only a part of the page is dynamically updated.

If you open the index.html in any of the angular applications, you would see the following HTML markup

                              
 
<body>
    <app-root>Loading...</app-root>
</body>
 
                            
                        

The "app-root" is a placeholder (selector), which is defined in the root component.

Angular generates and loads the view associated with the root component inside the "app-root". Any subsequent components are also loaded dynamically inside the "app-root" selector

Angular does all this behind the scenes.

In such a scenario, we are not required to change the URL. But that brings a few cons

  • You won't be able to refresh the page
  • You won't be able to go to a particular view by typing the URL
  • Sharing the URL with someone is not possible
  • The Back button will not work as you cannot go back to the previous page
  • SEO is not possible
  • That is where the client-side routing comes into the picture

    The Client-side routing simply mimics server-side routing by running the process in the browser. It changes the URL in the browser address bar and updates the browser history, without actually sending the request to the server

    How Client-Side Routing works

    The Client-side routing is handled in two ways

  • Hash style Routing
  • HTML 5 Routing
  • Hash Style Routing

    The Hash style routing uses the anchor tags technique to achieve client-side routing.

    The anchor tags, when used along with the # allows us to jump to a place, within the web page.

    For Example

    Index.html
                                  
    
    <a name="contact">Contact Us</a>
                                
                            

    When we visited the URL http://mysite.com/index.html#contact, the browser would scroll to the location of the Contact us label

    When the requested anchor tag is on the current page, then the browser does not send the request to the Web server.

    The Hashstyle Routing uses this technique to create the URL

    The URL would look something like

                                  
    
    http://www.example.com
    http://www.example.com/#/about
    http://www.example.com/#/contact
     
                                
                            

    In all the above examples, only the URL sent to the server is http://www.example.com the URL's "#/about" and #/contact is never sent to the server

    HTML 5 routing

    The introduction of HTML5, now allows browsers to programmatically alter the browser's history through the history object.

    Using history.pushState() method, we can now programmatically add the browser history entries and change the location without triggering a server page request.

    1. State object: A state object is a JavaScript object which is associated with the new history entry created by pushState()
    2. Title: This is an optional title for the state
    3. URL: The new history entry’s URL. The browser won’t jump to that page.
                                  
    
    var stateObj= { message: "some message" };
    history.pushState(stateObj, "title", newUrl);
     
                                
                            

    Using history.pushState the method, The browser creates new history entries that change the displayed URL without the need for a new request.

    Example

    When you request for http://www.example.com the server sends the index.html

    Now, When you click on ProductList link, Angular use’s the history.pushState method to push the state and change the URL to http://www.example.com/ProductList

    Now, when you click on the specific Product, we again the use history method to push the state and change the URL to http://www.example.com/product/1

    Here, when you click the back button, the browser will retrieve the http://www.example.com/ProductList from history and displays it.

    But there are cons to this approach

    1. Not all browsers support HTML 5
    2. The older browser does not support HTML5. So if you want to support older browsers, you have to stick to the hash-style routing

    Why is Server Support Needed for HTML 5 routing

    Now, consider the above example

    What would happen, when you type the URL http://www.example.com/ProductList and hit the refresh button.

    The browser will send the request to the web server. Since the page ProductList does not exist, it will return the 404 (page not found) error.

    This problem could be solved, if we are able to redirect all the requests to the index.html

    It means that when you ask from http://www.example.com/ProductList, the Web server must redirect it to index.html and return the request. Then in the Front-end Angular will read the URL and dynamically load the ProductListComponent.

    To make HTML5 routing work you need to send the instruction to the webserver to serve < /index.html> for any incoming request, no matter what the path is.

    Location Strategy

    As mentioned earlier, Angular implements both Hashstyle & HTML 5 Routing. HashLocationstrategy implements the Hashstyle routing & Pathlocationstrategy implements the HTML5 style routing

    PathLocationStrategy Vs HashLocationStrategy

    PathLocationStrategy

    Pros:
  • Produces a clear URL like http://example.com/foo
  • Supports Server-Side Rendering
  • Cons:

    1. Older browser does not support
    2. Server Support needed for this to work

    HashLocationStrategy

    Pros:
  • Supported by all browsers
  • Cons:
  • Produces a URL like http://example.com/#foo
  • Will not Support Server-Side Rendering
  • PathLocationStrategy

    The PathLocationStrategy is the default strategy in the Angular application.

    To Configure the strategy, we need to add <base href> in the section of the root page (index.html) of our application

                                  
    
    <base href="/">
                                
                            

    The Browser uses this element to construct the relative URLs for static resources (images, CSS, scripts) contained in the document.

    If you do not have access to <head> Section of the index.html, then you can follow either of the two steps

    Add the APP_BASE_HREF value as shown in the provider’s section of the root module

                                  
    
    import {Component, NgModule} from '@angular/core';
    import {APP_BASE_HREF} from '@angular/common';
     
    @NgModule({
    providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
    })
    class AppModule {}
                                
                            

    Here, when you click the back button, the browser will retrieve the http://www.example.com/ProductList from history and displays it.

    or use the absolute path for all the static resources like CSS, images, scripts, and HTML files.

    HashLocationStrategy

    You can use the HashLocationStrategy by providing the useHash: true in an object as the second argument of the RouterModule.forRoot in the AppModule.

                                  
    
    @NgModule,({
    declarations: [
        AppComponent,HomeComponent,ContactComponent,ProductComponent,ErrorComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        Hashlocationstrategy RouterModule.forRoot(appRoutes, { useHash: true }
    ],
    providers: [ProductService],
    bootstrap: [AppComponent]
    })
     
                                
                            

    Which Location Strategy to Use

    We recommend you use the HTML 5 style (PathLocationStrategy) as your location strategy.

    Because

  • It produces clean and SEO Friendly URLs that are easier for users to understand and remember.
  • You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering them the client
  • Use the hash location strategy only if you have to support older browsers.

    Summary

    Angular supports two different location strategies or Routing strategies in Angular. One is PathlocationStrategy and the other one is HashLocationStrategy. The HashLocationStrategy use the Hash style routing, while PathlocationStrategy uses the HTML 5 Routing.